<template>
  <div class="app-container">
    <el-form @submit.native.prevent :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
             label-width="68px">
      <el-form-item label="真实姓名" prop="name">
        <el-input
          v-model="data.name"
          placeholder="真实姓名"
          clearable
          @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleUpdate(null,'添加')"
          v-hasPermi="['zhcloud:sub:add']"
        >添加
        </el-button>
      </el-col>
    </el-row>
    <el-table v-loading="loading" :data="list" :height="tableHeight">
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="360px" fixed="left">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,'修改昵称')"
            v-hasPermi="['zhcloud:sub:nickname']"
          >修改昵称
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,'删除')"
            v-hasPermi="['zhcloud:sub:del']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,'分配权限')"
            v-hasPermi="['zhcloud:sub:permission']"
          >分配权限
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row,'选择仓库')"
            v-hasPermi="['zhcloud:sub:warehouse']"
          >选择仓库
          </el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleResetPwd(scope.row)"
            v-hasPermi="['system:user:resetPwd']"
          >密码修改
          </el-button>
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            @click="handleUpdate(scope.row,'是否屏蔽客户')"-->
<!--            v-hasPermi="['zhcloud:sub:client']"-->
<!--          >是否屏蔽客户-->
<!--          </el-button>-->
        </template>
      </el-table-column>
      <af-table-column label="账号" align="center" prop="UserName" fixed="left"/>
      <af-table-column label="昵称" align="center" prop="Nick"/>
      <!--      <af-table-column label="权限" align="center" prop="RoleName"/>-->
<!--      <af-table-column label="是否屏蔽客户" align="center" prop="khpbT"/>-->
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-drawer :title="title" :visible.sync="open" size="35%">
      <div style="padding-left: 25px">
        <p style="color: red;">默认不选择显示所有仓库</p>
        <el-checkbox-group v-model="form.selectWarehouses">
          <el-checkbox v-for="(item,index) in loadWarehouses" :label="item.spckid" :key="index"
                       style="display:inline-block;width: 225px">{{item.spckmc}}
          </el-checkbox>
        </el-checkbox-group>
        <el-button style="margin-top: 15px" type="primary" @click="submitForm">修改</el-button>
      </div>
    </el-drawer>
    <el-drawer :title="sub.title" :visible.sync="sub.open" size="35%">
      <el-form ref="subForm" :model="sub.form" label-width="100px" :rules="sub.rules" style="width: 95%;">
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="sub.form.username" autocomplete="new-text"
            placeholder="用户名"
            clearable/>
        </el-form-item>
        <el-form-item label="姓名" prop="nickname">
          <el-input
            v-model="sub.form.nickname" autocomplete="new-text"
            placeholder="姓名"
            clearable/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="sub.form.password" autocomplete="new-password"
            placeholder="密码"
            clearable/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="sub.form.remark" autocomplete="new-text"
            placeholder="备注"
            clearable/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="addSubAccount">提交</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-dialog :title="permission.title" :visible.sync="permission.open" width="500px" append-to-body>
      <el-form ref="form" :model="permission.form" :rules="permission.rules" label-width="100px">
        <el-form-item label="菜单权限">
          <el-tree
            class="tree-border"
            :data="permission.menuOptions"
            :default-expanded-keys="permission.checkedKeys"
            :default-checked-keys="permission.checkedKeys"
            show-checkbox
            ref="permission"
            node-key="id"
            empty-text="加载中，请稍候"
            :props="permission.defaultProps"
          ></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPermissionForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {list, updateUserKhpb, updateUserNickName, delUser, updateUserSpckid,addSubAccount} from "@/api/shop/sub-account-api";
  import {selectWarehouse} from "@/api/zdspck/api";
  import {resetUserPwd, corporateMenu, updateSubUserMenu} from "@/api/system/user";

  export default {
    name: "Sub-account",
    data() {
      return {
        sub: {
          title: '',
          open: false,
          form: {
            username: '',
            password: '',
            nickname: '',
            remark: '',
          },
          rules:{
            username: [
              { required: true, trigger: "blur", message: "请输入您的用户名" },
              { min: 5, max: 20, message: '用户名长度必须介于 5 和 20 之间', trigger: 'blur' }
            ],
            nickname: [
              { required: true, trigger: "blur", message: "请输入您的姓名" },
              { min: 2, max: 20, message: '姓名长度必须介于 2 和 20 之间', trigger: 'blur' }
            ],
            password: [
              { required: true, trigger: "blur", message: "请输入您的密码" },
              { min: 5, max: 20, message: '密码长度必须介于 5 和 20 之间', trigger: 'blur' }
            ],
          }
        },
        permission: {
          // 菜单列表
          menuOptions: [],
          checkedKeys: [],
          form: {},
          title: '',
          open: false,
          defaultProps: {
            children: "children",
            label: "label"
          },
        },
        title: '',
        open: false,
        form: {
          selectWarehouses: [],
          userId: ''
        },
        clientHeight: document.documentElement.clientHeight,
        tableHeight: 500,// 定义table高度
        // 遮罩层
        loading: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 仓库表格数据
        list: [],
        loadWarehouses: [],
        // 页码
        queryParams: {
          pageNum: 1,
          pageSize: 10
        },
        // 页码
        data: {
          name: ''
        }
      };
    },
    mounted() {
      //  重置浏览器高度
      window.onresize = () => {
        this.clientHeight = document.documentElement.clientHeight;
      }
    },
    created() {
      this.getList();
      selectWarehouse().then(response => {
        this.loadWarehouses = response.data;
      })
    },
    methods: {
      addSubAccount(){
        this.$refs.subForm.validate(valid => {
          if (valid) {
            addSubAccount(this.sub.form).then(response => {
              if (response.code !== 200) {
                this.$modal.msgError(response.msg);
              } else {
                this.$modal.msgSuccess("保存成功");
                this.getList();
                this.sub.open = false;
              }
            })
          }
        });
      },
      submitPermissionForm() {
        updateSubUserMenu(this.getMenuAllCheckedKeys(), this.permission.form.userId).then(response => {
          if (response.code !== 200) {
            this.$modal.msgError(response.msg);
          } else {
            this.$modal.msgSuccess("保存成功");
            this.getList();
            this.permission.open = false;
          }
        })
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.permission.getCheckedKeys();
        // 半选中的菜单节点
        let halfCheckedKeys = this.$refs.permission.getHalfCheckedKeys();
        checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
        return checkedKeys;
      },
      submitForm() {
        this.loading = true;
        this.form.spckid = this.form.selectWarehouses.join(",")
        updateUserSpckid(this.form).then(response => {
          if (response.code !== 200) {
            this.$modal.msgError(response.msg);
          } else {
            this.$modal.msgSuccess("保存成功");
            this.getList();
            this.open = false;
          }
          this.loading = false;
        });
      },
      /** 重置密码按钮操作 */
      handleResetPwd(row) {
        this.$prompt('请输入"' + row.UserName + '"的新密码', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          closeOnClickModal: false,
          inputPattern: /^.{5,20}$/,
          inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
        }).then(({value}) => {
          resetUserPwd(row.Id, value).then(response => {
            this.$modal.msgSuccess("修改成功，新密码是：" + value);
          });
        }).catch(() => {
        });
      },
      handleUpdate(row, type) {
        if ('是否屏蔽客户' === type) {
          this.$confirm('确定修改屏蔽客户属性', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let data = {}
            data.userId = row.Id
            data.khpb = row.khpb === 0 ? 1 : 0
            updateUserKhpb(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }).catch(() => {
          });
        }
        if ('修改昵称' === type) {
          this.$prompt('昵称', "修改昵称", {
            inputValue: row.Nick,
            confirmButtonText: "确定",
            cancelButtonText: "取消"
          }).then(({value}) => {
            let data = {}
            data.userId = row.Id
            data.nickName = value
            updateUserNickName(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          }).catch(() => {
          });
        }
        if ('删除' === type) {
          this.$confirm('确定删除么', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let data = {}
            data.userId = row.Id
            delUser(data).then(response => {
              this.$modal.msgSuccess("删除成功");
              this.open = false;
              this.getList();
            });
          }).catch(() => {
          });
        }
        if ('分配权限' === type) {
          this.permission.open = true;
          this.permission.title = type;
          corporateMenu(row.Id).then(response => {
            this.permission.menuOptions = response.menus;
            this.permission.checkedKeys = response.checkedKeys;
          })
          this.permission.form.userId = row.Id
        }
        if ('选择仓库' === type) {
          this.open = true;
          this.title = type;
          this.form.userId = row.Id
          this.form.selectWarehouses = [];
          if (row.spckid && row.spckid !== '') {
            row.spckid.split(",").forEach(e => this.form.selectWarehouses.push(e))
          }
        }
        if ('添加' === type) {
          this.sub.open = true;
          this.sub.title = type;
          this.sub.form = {
            username: '',
            password: '',
            nickname: '',
            remark: '',
          }
        }
      },
      getList() {
        this.loading = true;
        list(this.data, this.queryParams).then(response => {
          this.list = response.rows;
          this.total = response.total;
          this.loading = false;
        });
        //  初始值，自己定义
        this.tableHeight = this.clientHeight - 280
      },
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      }
    }
  };
</script>
